package com.my.programmtic;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 编程式事务管理之命令式 - 通过PlatformTransactionManager来实现事务管理
 *
 * @author: marshal
 * @date: 2023-05-24 15:08
 */
public class ImperativeTransactionManagerService {

    private final PlatformTransactionManager txManager;

    public ImperativeTransactionManagerService(PlatformTransactionManager txManager) {
        this.txManager = txManager;
    }


    public void testTransaction() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("SomeTxName");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);

        try {
            // 业务代码
            update1();
            update2();
        } catch (Exception e) {
            // 事务回滚
            txManager.rollback(status);
        }
        // 提交事务
        txManager.commit(status);
    }


    public Integer update1(){
        System.out.println("this is update1");
        return 1;
    }

    public Integer update2() {
        System.out.println("this is update2");
        return 2;
    }
}
